<?php
declare (strict_types=1);

namespace app\admin\controller\admin;

use think\App;
use app\admin\controller\Admin;
use app\admin\annotation\common\Auth;
use app\admin\service\dev\FieldService;
use app\admin\model\admin\User as UserModel;
use app\admin\validate\admin\User as UserValidate;
use app\admin\model\dev\Menu;
use app\admin\service\common\SmartMockGenerator;
use app\common\Constants;
use Faker\Factory;
use think\facade\Lang;
use think\facade\Db;
use app\admin\service\common\SortableService;


class BaseUser extends Admin
{
    public function __construct(
        App $app,
        protected UserModel  $userModel,
    )
    {
        parent::__construct($app);
    }
    
    #[Auth('admin:user:index')]
    public function index(): \think\response\Json
    {
        $param = $this->request->post();
        try { 
            // 查询
            $query = $this->userModel->withPerms(true);
            
            // 搜索主键 提交的是以逗号隔开的id字符串
            $query->when(isset($param['id']), function ($query) use ($param) {
                $query->whereIn('id', $param['id']);
            }); 

            // 搜索用户名
            $query->when(isset($param['username']), function ($query) use ($param) {
                $keyword = str_replace(['%', '_'], ['\%', '\_'], $param['username']);
                $query->whereLike('username', "%" . $keyword . "%");
            }); 
            // 搜索邮箱
            $query->when(isset($param['email']), function ($query) use ($param) {
                $keyword = str_replace(['%', '_'], ['\%', '\_'], $param['email']);
                $query->whereLike('email', "%" . $keyword . "%");
            }); 
            // 搜索电话
            $query->when(isset($param['mobile']), function ($query) use ($param) {
                $keyword = str_replace(['%', '_'], ['\%', '\_'], $param['mobile']);
                $query->whereLike('mobile', "%" . $keyword . "%");
            }); 
            // 搜索角色
            $query->when(isset($param['role_ids']), function ($query) use ($param) {
                $query->where('role_ids', '=', $param['role_ids']);
            }); 
            
            // 排序
            $order_by = sort_rules($param['order_by'] ?? 'sort|desc');
            $query->order($order_by);
            
            // 分页
            $page_size = $param['page_size'] ?? 20;
            $current_page = $param['current_page'] ?? 1;
            
            // 查询
            $list = $query->paginate(['list_rows' => $page_size, 'page' => $current_page,])->toArray();
            $list['sort'] = $order_by;
            
            // 增加选项数据
            $pathinfo = $this->request->pathinfo();
            $list['options'] = FieldService::getMenuOptions($pathinfo);
            
            // 返回数据
            return $this->success(['data' => $list]);
        } catch (\think\Exception\ValidateException $ve) {
            return $this->error(['msg' => $ve->getMessage()]);
        } catch (\Exception $e) {
            throw $e;
        }
    } 



    #[Auth('admin:user:modify')]
    public function modify(): \think\response\Json
    {
        $params = $this->request->param(['id', 'field', 'value']);
        validate(UserValidate::class)->scene('modify')->check($params);
        $role = $this->userModel->findOrFail($params['id']);
        $field = $params['field'];
        $role->$field = $params['value'];
        $role->save();
        return $this->success();
    } 



   #[Auth('admin:user:add')]
   public function add(): \think\response\Json
   {
       $post = $this->request->post();
        try {
            // 参数验证
            validate(UserValidate::class)->scene('add')->check($post);
            // 新增
            $this->userModel->create($post);
            // 返回
            return $this->success();
        } catch (\think\Exception\ValidateException $ve) {
            return $this->error(['msg' => $ve->getMessage()]);
        } catch (\Exception $e) {
            throw $e;
        }
    } 



    #[Auth('admin:user:update')]
    public function update(): \think\response\Json
    {
       $post = $this->request->post();
        try {
            // 参数验证
            validate(UserValidate::class)->scene('update')->check($post);
            // 查询
            $result = $this->userModel->findOrFail($post['id']);
            // 修改
            $result->save($post);
            // 返回
            return $this->success();
        } catch (\think\Exception\ValidateException $ve) {
            return $this->error(['msg' => $ve->getMessage()]);
        } catch (\Exception $e) {
            throw $e;
        }
    } 

    #[Auth('admin:user:update')]
    public function getFormData(): \think\response\Json
    {
        $id = $this->request->param('id/d');
        $result = $this->userModel->findOrFail($id);
        return $this->success(['data' => $result]);
    } 



    #[Auth('admin:user:delete')]
    public function delete(): \think\response\Json
    {
        $ids = $this->request->post('id/a');
        validate(UserValidate::class)->scene('delete')->check(['ids' => $ids]);
        $count = $this->userModel->destroy($ids);
        return $this->success(['data' => $count]);
    } 



    #[Auth('admin:user:detail')]
    public function detail(): \think\response\Json
    {
        $id = $this->request->param('id/d');
        $query = $this->userModel->withPerms(false);
        $result = $query->findOrFail($id);
        return $this->success(['data' => $result]);
    } 



    #[Auth('admin:user:reset')]
    public function reset(): \think\response\Json
    {
        $post = $this->request->post();
        $model = $this->userModel->findOrFail($post['id']);
        $model->password = $post['password'];
        $model->save();
        return $this->success();
    }

    #[Auth('admin:user:drag')]
    public function drag(): \think\response\Json
    {
        $fields = ['newId','oldId','dragPos','orderBy','dragToChild'];
        $data = $this->request->only($fields, 'post');
        SortableService::sortWithModel($this->userModel, $data);
        return $this->success();
    } 





    // 这是结束位置
}